package com.huaqin.salestracker;

import java.util.ArrayList;
import java.util.HashMap;

import com.huaqin.common.NVRAM;
import com.huaqin.common.Util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SalesTrackerActivity extends Activity {

	private static final String TAG = "SalesTrackerActivity";
	private static final String SYSTEM_VERSION = "2012.12.24_1.0.0_Beta";
	private static ListView mListView = null;
	private static ListReadAdapter mListAdapter = null;
	private static int mCurrentPosition = -1;
	private static final int MSG_UPDATE_LIST = 1;
	private static final int MSG_CLEAR_LIST =2;
	private TextView mCurrentStatus = null;
	private ProgressBar mProgressBar = null;
	private String mCurrentStatusText = null;

	private Button mBtnReset = null;
	private Button mBtnStart = null;
	private Button mBtnStop = null;

	private boolean mRegister = false;
	private boolean mIsDebug = false;
	private boolean mServiceRun = false;

	public static final String CMD_UPDATE_STATUS = "com.huaqin.salesactivity.update";
	
	private static ArrayList<HashMap<String, Object>> mItemList = null;
	private String[] mCheckItem = null;
	private MyHandler mHandler = null;

	private transient BroadcastReceiver mReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent != null){
				if(intent.getAction().equals(CMD_UPDATE_STATUS)){

					String systemstatus = intent.getStringExtra("status");
					String description = intent.getStringExtra("description");
					
					Log.i(TAG, "onReceive:" + systemstatus);
			    	updateCurrentStatus(systemstatus, description);
			    	updateServiceRunFlag();
				}
			}
		}

	};

	private View.OnClickListener mButtonListener = new View.OnClickListener(){

		@Override
		public void onClick(final View view) {
			// TODO Auto-generated method stub

			switch(view.getId()){
				
				case R.id.reset:

					Log.i(TAG, "NVRAM Reset!");
					
					NVRAM.Reset();

					mBtnStart.setEnabled(true);
					mBtnStop.setEnabled(false);
					
					break;
					
				case R.id.starttest:
					
					Log.i(TAG, "Start Service!");

					mProgressBar.setVisibility(View.VISIBLE);
					
					Intent startService =  new Intent(SalesTrackerActivity.this, SalesTrackerService.class);
					startService.setAction(SalesTrackerService.STCMD_START_ACTION);
			        SalesTrackerActivity.this.startService(startService);
			        
			        if(mServiceRun){
			            setServiceBrodcast(true);
			        }

					mBtnStart.setEnabled(false);
					mBtnStop.setEnabled(true);

					break;

				case R.id.stoptest:
					
					Log.i(TAG, "Stop Service!");
					
					mProgressBar.setVisibility(View.INVISIBLE);
					
					Intent stopService =  new Intent(SalesTrackerActivity.this, SalesTrackerService.class);
					stopService.setAction(SalesTrackerService.STCMD_STOP_ACTION);
			        SalesTrackerActivity.this.startService(stopService);

					mBtnStart.setEnabled(true);
					mBtnStop.setEnabled(false);
					
					break;
					
				default:
					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		Log.i(TAG, ">> onCreate()");
	    setContentView(R.layout.sales_tracer_develop_layout);
	    
		mRegister = NVRAM.isRegister();
		mIsDebug = SalesTrackerService.mSystemDebug;
		updateServiceRunFlag();

		mCurrentStatus = (TextView) findViewById (R.id.status );
		mProgressBar = (ProgressBar) findViewById (R.id.progressBar);

	    mListView = (ListView)findViewById(R.id.resultlist);
	    mListView.setVisibility(View.VISIBLE);
	    
	    mItemList = new ArrayList<HashMap<String, Object>>();
	    
        mListAdapter = new ListReadAdapter(this, mItemList, R.layout.center_vertical);
        mListView.setAdapter(mListAdapter);
        
        mCheckItem = getResources().getStringArray(R.array.perf_allow_tester_modify);

		mBtnReset = (Button)findViewById(R.id.reset);
		mBtnStart = (Button)findViewById(R.id.starttest);
		mBtnStop = (Button)findViewById(R.id.stoptest);

		updateCurrentStatus(null, null);
		
		if(mServiceRun){
		    
		    if (!mRegister){
	            mListView.setOnItemClickListener(new OnItemClickListener(){

	                @Override
	                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	                    // TODO Auto-generated method stub
	                    mCurrentPosition = position;    
	                    showDialog(itemCheck((String)mItemList.get(mCurrentPosition).get("item")));
	                }
	                
	            }); 
	        }
	        else {
	            mBtnStop.setEnabled(false);
	        }

            mBtnStart.setEnabled(false);
            
        }
        else{
            mProgressBar.setVisibility(View.INVISIBLE);
            mBtnStop.setEnabled(false);
        }

		if(!mRegister){
		    mBtnReset.setEnabled(false);
		}
		else{
		    mBtnStart.setEnabled(false);
		}

		mBtnReset.setOnClickListener(mButtonListener);
		mBtnStart.setOnClickListener(mButtonListener);
		mBtnStop.setOnClickListener(mButtonListener);
		
		if(mServiceRun){
		    IntentFilter filter = new IntentFilter();
	        filter.addAction(CMD_UPDATE_STATUS);
	        registerReceiver(mReceiver, filter);
		}

		Log.i(TAG, "<< onCreate()");
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		Log.i(TAG, ">> onStart()");
		
        if(mServiceRun){
            setServiceBrodcast(true);
            
            if(mHandler == null){
                mHandler = new MyHandler();
            }
            mHandler.sendEmptyMessage(MSG_UPDATE_LIST);
        }

	}
	
	//Notice Service send Refresh Broadcast
	private void setServiceBrodcast(boolean visible){
		if (!mRegister){
		    Intent intent = new Intent(this, SalesTrackerService.class);
	        intent.setAction(SalesTrackerService.STCMD_UPDATE_ACTION);
	        intent.putExtra(SalesTrackerService.KEY_VISIBLE, visible);
	        startService(intent);
		}
	}

	private class ListReadAdapter extends SimpleAdapter{
		private ArrayList<HashMap<String, Object>> data; 
		private final int layoutResource;
		
		public ListReadAdapter(Context context, ArrayList<HashMap<String, Object>> data, int resource) {
			super(context, data, resource, null, null); 
			// TODO Auto-generated constructor stub
			this.data = data; 
			this.layoutResource = resource;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
		    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		    View view = layoutInflater.inflate(layoutResource, null); 

			ViewHolder item = new ViewHolder();

            item.extractItem = (TextView)view.findViewById(R.id.extract_item);  
			item.extractValues = (TextView)view.findViewById(R.id.extract_values);
			
			String itemName = data.get(position).get("item").toString();
			item.extractItem.setText(itemName);
			
			if(itemCheck(itemName)){
			    item.extractItem.setTextColor(Color.GREEN);
			}

			item.extractValues.setText(data.get(position).get("value").toString());

			return view;  
		}
	}

	class ViewHolder{
        private TextView extractItem;
        private TextView extractValues;
    }
	
	class MyHandler extends Handler{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			switch(msg.what){
				case MSG_UPDATE_LIST:
					updateList();
					break;
					
				case MSG_CLEAR_LIST:
					clearList();
					break;
					
				default:
					break;
			}
		}
	}

	private void showDialog(boolean bool){

		if (bool){
			final EditText edittext = new EditText(this);
			
			edittext.setText((String)mItemList.get(mCurrentPosition).get("value"));
			edittext.setSingleLine();

			new AlertDialog.Builder(this).setTitle((String)mItemList.get(mCurrentPosition).get("item"))
				.setIcon(android.R.drawable.ic_dialog_info).setView(edittext)
				.setPositiveButton(getString(R.string.dialog_confirm), new DialogInterface.OnClickListener() {
												
												@Override
												public void onClick(DialogInterface dialog, int which) {
													// TODO Auto-generated method stub
													HashMap<String, Object> Item = mItemList.get(mCurrentPosition);

													String dest = edittext.getText().toString();
													if(inputCheck((String)Item.get("value"), dest)){
													    String Value = edittext.getText().toString();
                                                        Item.put("value", Value);
                                                        mItemList.set(mCurrentPosition, Item);

                                                        mListAdapter.notifyDataSetChanged();
                                                        mListView.setSelection(mCurrentPosition);
                                                        
                                                        //Broadcast Service update config
                                                        Intent send = new Intent(SalesTrackerActivity.this, SalesTrackerService.class);
                                                        send.setAction(SalesTrackerService.STCMD_UPDATE_CONFIG);
                                                        send.putExtra("Index", mCurrentPosition);
                                                        send.putExtra("Value", Value);
                                                        SalesTrackerActivity.this.startService(send);
													}
													else{
													    new AlertDialog.Builder(SalesTrackerActivity.this)
                                                        .setTitle((String)mItemList.get(mCurrentPosition).get("item"))
                                                        .setIcon(android.R.drawable.ic_dialog_alert)
                                                        .setMessage(getString(R.string.dialog_error_input))
                                                        .setNegativeButton(getString(R.string.dialog_cancel), null).show();
													}
												}
											})
											.setNegativeButton(getString(R.string.dialog_cancel), null).show();
		}
		else{
			new AlertDialog.Builder(this).setTitle((String)mItemList.get(mCurrentPosition).get("item"))
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setMessage(getString(R.string.dialog_unmodify))
				.setNegativeButton(getString(R.string.dialog_cancel), null).show();
		}
		
	}

	private void updateList(){

		if (mItemList.isEmpty() && SalesTrackerService.mConfigItemList != null
		        && !SalesTrackerService.mConfigItemList.isEmpty()){
			int length = SalesTrackerService.mConfigItemList.size();
			for (int i = 0; i < length; i++){
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("item", SalesTrackerService.mConfigItemList.get(i).get("item")); 
                item.put("value", SalesTrackerService.mConfigItemList.get(i).get("value"));
                mItemList.add(item);
			}
		}
		
		mListAdapter.notifyDataSetChanged();
		mListView.setSelection(mItemList.size());
	}

	private void clearList() {
	    if(mItemList != null){
	        mItemList.clear();
	        mListAdapter.notifyDataSetChanged(); 
	    }
	}
	
	private boolean itemCheck(String item){
	    boolean ret = false;
		if(mCheckItem != null && item != null){
		    for (int i = 0; i < mCheckItem.length; i++){
	            if (item.equals(mCheckItem[i])){
	                ret = true;
	                break;
	            } 
	        }
		}
		
		return ret;
	}
	
	private boolean inputCheck(String src, String dest){
	    boolean ret = false;
		if (src != null && dest != null && !src.equalsIgnoreCase(dest)){
		    if (Util.isPhoneNumber(src) || Util.isHttpUrl(src)){
	            if (Util.isPhoneNumber(dest) || Util.isHttpUrl(dest)){
	                ret = true;
	            }
	        }
	        else if (Util.isLogicString(src) && Util.isLogicString(dest)){
	            ret = true;
	        }
	        else if (Util.isTimeOrInterval(src) && Util.isTimeOrInterval(dest)){
	            ret = true;
	        }
		}
		else{
		    Log.e(TAG, "Illicit Input: " + dest);
		}

		return ret;
	}
	
	private void updateServiceRunFlag(){
	    mServiceRun = isServiceRun();
	}
	
	private boolean isServiceRun(){

	    ActivityManager myManager=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
	    ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
	    for(int i = 0 ; i<runningService.size();i++){
	        String serviceName = runningService.get(i).service.getClassName().toString();
	        if(serviceName.equals("com.huaqin.salestracker.SalesTrackerService")){
	            return true; 
	        }
	    }
	    
	    return false;
	}

	private void updateCurrentStatus(String status, String description){
		String temp = "";
		String SystemInfo = Util.getStringPref(this, SalesTrackerSLable.APP, "None");

		mCurrentStatusText = getString(R.string.app_name) + ": " + SystemInfo + "\n";
		
		if(!mIsDebug){
		    mCurrentStatusText += getString(R.string.version) + SYSTEM_VERSION + "\n";
		}
		
		if (SystemInfo != null && SystemInfo.equals(SalesTrackerService.HUAQIN_APP)){
		    if(mRegister){
		        mCurrentStatusText += getString(R.string.current_status)
		                + getString(R.string.register) + "\n";
		        mCurrentStatusText += getString(R.string.register_time) + 
		                NVRAM.getRegisterTime() + "\n";
		    }
		    else{
		        mCurrentStatusText += getString(R.string.current_status) 
		                + getString(R.string.unregister) + "\n";
		    }
		}

		if (!mRegister) {
			mCurrentStatusText += getString(R.string.executestatus) + status + "\n";
		}
		
		if(description != null){
		    mCurrentStatusText += getString(R.string.currentcondition) + description;
		}

		if(SalesTrackerService.mIsRetry && !mRegister) {
			temp = ((SalesTrackerService.mRetrySend > 0) ? getString(R.string.retry) + "\n>"
					+ getString(R.string.retrytime) + ":" + SalesTrackerService.mRetryTime + "\n>" 
					+ getString(R.string.currentretrytime) + ":" + SalesTrackerService.mRetrySend + "\n>" 
					+ getString(R.string.retryinterval) + ":" + SalesTrackerService.mRetryInterval: "");
			
			mCurrentStatusText += temp;
		}
		
		if (SalesTrackerService.mIsFeedback && !mRegister){
			temp = ((SalesTrackerService.mFeedbackSend > 0) ? getString(R.string.feedback) +"\n>" 
					+ getString(R.string.feedbacktime) + ":" + SalesTrackerService.mFeedbackTime + "\n>" 
					+ getString(R.string.currentfeedabcktime) + ":" + SalesTrackerService.mFeedbackSend +"\n>" 
					+ getString(R.string.feedbackinterval) + ":" + SalesTrackerService.mFeedbackInterval : "");
			
			mCurrentStatusText += temp;
		}
		
		mCurrentStatus.setText(mCurrentStatusText);
	}

	@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Log.i(TAG, ">> onBackPressed()");
        finish();
    }

    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(TAG, ">> onResume()");
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(mServiceRun){
		    mHandler.sendEmptyMessage(MSG_CLEAR_LIST);
		}
		Log.i(TAG, ">> onPause()");
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i(TAG, ">> onStop()");
		finish();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(mItemList != null){
		    mItemList.clear();
		    mItemList = null;
		}
		
		try {
		    updateServiceRunFlag();
	        if(mServiceRun){
	            setServiceBrodcast(false);
	            unregisterReceiver(mReceiver);
	        }
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG,"onDestroy() unregisterReceiver mReceiver Exception");
        }

		Log.i(TAG, ">> onDestroy()");
		super.onDestroy();
	}

	
}
